#include "HttpResponse.hpp"

std::map<HttpStatusCode, std::string> statusCommentMap {
    {HttpStatusCode::OK, "OK"},
    {HttpStatusCode::SwitchingProtocols, "SwitchingProtocols"},
    {HttpStatusCode::PartialContent, "PartialContent"},
    {HttpStatusCode::NotFound, "NotFound"},
    {HttpStatusCode::Forbidden, "Forbidden"},
    {HttpStatusCode::MethodNotAllowed, "MethodNotAllowed"},
    {HttpStatusCode::InternalServerError, "InternalServerError"},
    {HttpStatusCode::GatewayTimeout, "GatewayTimeout"},
    {HttpStatusCode::MoveTemporarily, "MoveTemporarily"},
    {HttpStatusCode::MovedPermanently, "MovedPermanently"}
};

void HttpResponse::addHeader(const std::string& key, const std::string& value) {
    if (key.empty() || value.empty()) {
        return ;
    }
    respHeaders_.insert({key, value});
}

std::string HttpResponse::getHeader(const std::string& key) {
    if (respHeaders_.find(key) == respHeaders_.end()) {
        return std::string();
    }
    return respHeaders_[key];
}


void HttpResponse::addContent(const char* content, int size){
    content_ = const_cast<char *>(content);
    contentSize_ = size;
    addHeader("Content-Length", std::to_string(size));
}

int HttpResponse::writeBuffer(Buffer* outBuffer) {
    if (version_.empty()) version_ = "HTTP/1.1";
    if (status_ == HttpStatusCode::None) {
        status_ = HttpStatusCode::OK;
        statusComment_ = statusCommentMap[status_];
    }
    std::string statusString = std::to_string(static_cast<int>(status_));
    outBuffer->appendString(version_.c_str(), version_.size());
    outBuffer->appendString(" ", 1);
    outBuffer->appendString(statusString.c_str(), statusString.size());
    outBuffer->appendString(" ", 1);
    outBuffer->appendString(statusComment_.c_str(), statusComment_.size());
    outBuffer->appendString("\r\n", 2);

    for (auto it=respHeaders_.begin(); it!=respHeaders_.end(); ++it){
        outBuffer->appendString(it->first.c_str(), it->first.size());
        outBuffer->appendString(": ", 2);
        outBuffer->appendString(it->second.c_str(), it->second.size());
        outBuffer->appendString("\r\n", 2);
    }
    outBuffer->appendString("\r\n", 2);
    if (content_!=nullptr) outBuffer->appendString(content_, contentSize_);
}
